from Tkinter import *
import Tkinter
import thread
import engine



class scripteditor(object):
	tk = Tk()
	topframe = Frame(tk)
	txtCommandHistory = Tkinter.Text(tk)
	txtCommandResult = Tkinter.Text(tk)
	entry = Tkinter.Entry(tk, width=97)
	engine = engine.Engine

	def __init__(self, engine):
		self.engine  = engine
		
		self.tk.title("Python Interactive Environment")
		self.tk.grid_rowconfigure(0, weight=0)
		self.tk.grid_rowconfigure(1, weight=1)
		self.tk.grid_rowconfigure(2, weight=1)
		self.tk.grid_columnconfigure(0, weight=0)
		self.tk.grid_columnconfigure(1, weight=1)
		x = self.tk.winfo_screenwidth() - 480
		y = self.tk.winfo_screenheight() - 570
		self.tk.geometry("450x500+"+ `x`+"+" + `y`)
		self.tk.wm_attributes('-topmost', 1)

		lblCommand = Tkinter.Label(self.tk, text="Command:")
		lblCommand.grid(row=0,column=0,sticky=W)		
		self.entry.grid(row=0,column=1, sticky = E+W)
		btnPlay = Tkinter.Button(self.tk, text ="Execute!", command = self.executeEntry)
		btnPlay.grid(row=0,column=2)
		self.tk.bind('<Return>', (lambda e, b=btnPlay: btnPlay.invoke()))
		
		#Command history
		self.txtCommandHistory.grid(row=1,column=0,columnspan=2, sticky = E+W+N+S)
		scrollbar = Scrollbar(self.tk)
		scrollbar.grid(row=1,column=2, sticky = N + S)
		self.txtCommandHistory.yscrollcommand = scrollbar.set		
		scrollbar.config(command = self.txtCommandHistory.yview)

		#Command result history		
		self.txtCommandResult.grid(row=2,column=0, columnspan=2, sticky = E+W+N+S)
		scrollbar2 = Scrollbar(self.tk)
		scrollbar2.grid(row=2,column=2, sticky = N + S)
		self.txtCommandResult.yscrollcommand = scrollbar2.set		
		scrollbar2.config(command = self.txtCommandResult.yview)		
		
		
	def run(self):
		self.txtCommandResult.insert(1.0, open("greeting.txt").read())
		self.tk.mainloop()

	def executeEntry(self):
		script = self.entry.get()
		self.txtCommandHistory.insert(1.0, script + "\n")
		self.entry.delete(0, Tkinter.END)
		trace = self.engine.evalscript(script)
		print(trace)
		if trace is None:
			trace = "Success"
		self.txtCommandResult.insert(1.0, trace + "\n")

	